import { computed, ref, onUnmounted } from 'vue'
import { dayjs } from 'element-plus'

export const useCountDown = () => {
  const time = ref(0)
  //格式化时间
  const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))

  let interval = null

  const startCountDown = (currentTime) => {
    time.value = currentTime
    interval = setInterval(() => {
      time.value--
      if (time.value === 0) {
        clearInterval(interval)
      }
    }, 1000)
  }

  //组件销毁时清除定时器
  onUnmounted(() => {
    clearInterval(interval)
  })

  return {
    formatTime,
    startCountDown
  }
}
